package cn.cellcom.agent.online.client;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.cellcom.agent.common.AgentConstant;
import cn.cellcom.agent.online.TaskEngine;

/**
 * 客户端管理
 * 
 * @author zhengyj
 * 
 */
public class ClientManager {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	ClientDetectionTask clientDetectionTask = null;

	private static ClientManager manager = null;

	private ClientManager() {

	}

	public static ClientManager getInstance() {
		if (manager == null) {
			manager = new ClientManager();
			manager.init();
		}
		return manager;
	}

	public void init() {
		ClientDetectionTask clientDetectionTask = new ClientDetectionTask();
		TaskEngine.getInstance().scheduleAtFixedRate(clientDetectionTask, 3000, 3000);
	}

	class ClientDetectionTask extends TimerTask {

		// 访客N秒没有发起get，认为失效
		private int abandonTime = 10 * 1000;

		@Override
		public void run() {
			for (Client client : clients.values()) {
				int ab = abandonTime;
				if (client instanceof VisitorClient) {
					// 微信渠道并且存在会话数据则10分钟才失效
					VisitorClient vc = (VisitorClient) client;
					if ((vc.getChannelObject().getType().equals(AgentConstant.CHANNEL_TYPE.WECHAT.name())
							|| vc.getChannelObject().getType().equals(AgentConstant.CHANNEL_TYPE.QQ.name())) && vc.getIdMap().size() > 0) {
						ab = ab * 6 * 2;
					}
				}
				//System.out.println("---" + (System.currentTimeMillis() - client.getLastActiveGet()) + "---" + ab);
				//默认值为0，避免：Web首次访问的时候网络缓慢而很快被认为超时了
				if (client.getLastActiveGet() >0 && System.currentTimeMillis() - client.getLastActiveGet() > ab) {
					if (client instanceof VisitorClient) {
						log.info("[{}] client is abandoned by abandonTime[{}]", client.getId(), ab);
						VisitorClient vc = (VisitorClient) client;
						vc.overtime();
					} else if (client instanceof AgentClient) {
						AgentClient ac = (AgentClient) client;
					}
				} else {
					// 根据策略找一个最好的坐席
				}
			}
		}
	}

	/**
	 * 客户端管理
	 */
	private Map<String, Client> clients = new ConcurrentHashMap<String, Client>();
	private Map<String, Set<AgentClient>> agentsOfPid = new ConcurrentHashMap<String, Set<AgentClient>>();

	/**
	 * 移除访客端
	 * 
	 * @param id
	 * @return
	 */
	public Client remove(String id) {
		Client client = (Client) clients.remove(id);
		if(client instanceof AgentClient) {
			AgentClient ac = (AgentClient) client;
			if (agentsOfPid.get(ac.getPid()) != null) {
				agentsOfPid.get(ac.getPid()).remove(ac);
			}
		}
		return client;
	}

	public Client record(Client client) {
		if (client instanceof AgentClient) {
			AgentClient ac = (AgentClient) client;
			Set<AgentClient> set = agentsOfPid.get(ac.getPid());
			// 如果企业还没有Set则创建
			if (set == null) {
				synchronized ("record_" + client.getOrg()) {
					if (set == null) {
						set = new HashSet<AgentClient>();
						agentsOfPid.put(ac.getPid(), set);
					}
				}
			}
			set.add((AgentClient) client);
		} else {
			
		}
		return (Client) clients.put(client.getId(), client);
	}

	public Client getClient(String id) {
		if(StringUtils.isBlank(id)) {
			return null;
		}
		return clients.get(id);
	}

	public Set<String> getOnlineClients() {
		return clients.keySet();
	}

	public Set<AgentClient> getOnlineAgents(String pid) {
		return agentsOfPid.get(pid);
	}

}
